<template>
  <span>
    <div v-show="checkValue === 1">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="航班号"
                        prop="flyNo"
                        label-width="90px"
                        :rules="[
              {
                required: form.checkValue === 1 ? true : false,
                message: `请输入航班号`
              }
            ]">
            <el-input v-model.trim="form.flyNo"
                      minlength="4"
                      maxlength="8"
                      placeholder="请输入航班号"
                      onkeyup="this.value=this.value.replace(/[^\w]/g,'')"
                      @blur="getStation(1)"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="flyTime"
                        label="航班日期"
                        label-width="90px"
                        :rules="[
              {
                required: form.checkValue === 1 ? true : false,
                message: `请选择航班日期`
              }
            ]">
            <date-select v-model="form.flyTime"
                         :picker-options="pickerOptions"
                         popper-class="no-atTheMoment"
                         placeholder="请选择航班日期"
                         :clearable="false"
                         :type="'date'"
                         @input="handleFlyDate" />
          </el-form-item>
        </el-col>
      </el-row>
    </div>
    <div v-show="checkValue === 2">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="车次"
                        prop="trainNum"
                        label-width="90px"
                        :rules="[
              {
                required: form.checkValue === 2 ? true : false,
                message: `请输入车次`
              }
            ]">
            <el-input v-model.trim="form.trainNum"
                      minlength="2"
                      maxlength="6"
                      placeholder="请输入车次"
                      onkeyup="this.value=this.value.replace(/[^\w]/g,'')"
                      @blur="getStation(2)"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="日期"
                        prop="trainTime"
                        label-width="90px"
                        :rules="[
              {
                required: form.checkValue === 2 ? true : false,
                message: `请选择日期`
              }
            ]">
            <date-select v-model="form.trainTime"
                         :picker-options="pickerOptions"
                         popper-class="no-atTheMoment"
                         :clearable="false"
                         :type="'date'"
                         placeholder="请选择日期"
                         @input="handleTrainDate" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item prop="trainForm"
                        label="出发地"
                        label-width="90px"
                        :rules="[
              {
                required: form.checkValue === 2 ? true : false,
                message: `请选择出发地`
              }
            ]">
            <el-select v-model="form.trainForm"
                       placeholder="请选择"
                       @change="handleDeparture">
              <el-option v-for="(item, index) in departureList"
                         :key="item.stationName"
                         :label="item.stationName"
                         :value="item.stationName"
                         :disabled="toIndex == null || index < toIndex ? false : true">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="trainTo"
                        label="目的地"
                        label-width="90px"
                        :rules="[
              {
                required: form.checkValue === 2 ? true : false,
                message: `请选择目的地`
              }
            ]">
            <el-select v-model="form.trainTo"
                       placeholder="请选择"
                       @change="handleInput">
              <el-option v-for="(item, index) in destinationList"
                         :key="item.stationName"
                         :label="item.stationName"
                         :value="item.stationName"
                         :disabled="index > formIndex ? false : true">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </div>
    <electronic-reply-form v-show="checkValue === 3"
                           :num="1"
                           :form-info="formInfo"
                           @input="handleElectronic"
                           @electronic="handleElectronic" />
    <el-button v-show="!form.isThirdShow"
               type="primary"
               @click="handleSelect">+电子回单</el-button>
  </span>
</template>

<script>
import DateSelect from "@basic/date/DatePicker.vue";
import ElectronicReplyForm from "./ElectronicReplyForm.vue";
import { returnCompareTime } from "@/libs/util.js";
import { ere } from "@/api/index";
export default {
  name: "TrackSupplement",
  components: { DateSelect, ElectronicReplyForm },
  props: {
    checkValue: Number,
    formInfo: {
      type: Object,
      default: () => { }
    },
    process: {
      type: [String, Number],
      default: "2"
    }
  },
  data () {
    return {
      suppleType: this.suppleInfo,
      form: {},
      formIndex: null,
      toIndex: null,
      departureList: [],
      destinationList: [],
      isShowButton: false,
      pickerOptions: null // 时间选择限制 发货时间-收货时间
    };
  },
  created () {
    this.form = this.formInfo;
    this.pickerOptions = {
      disabledDate: (time) => {
        return (
          time.getTime() >= new Date(this.form.toTime).getTime() ||
          time.getTime() <=
          new Date(
            new Date(this.form.fromTime).setDate(
              new Date(this.form.fromTime).getDate() - 1
            )
          ).getTime()
        );
      },
      selectableRange: (() => {
        let timeString = this.$moment(this.form.fromTime)
          .format("YYYY-MM-DD HH:mm")
          .substring(11, this.form.fromTime.length);
        let time = timeString.substring(0, 2);
        let miumin = timeString.substring(3, timeString.length);
        if (Number(timeString.substring(3, timeString.length)) != 59) {
          miumin =
            miumin[0] == 0
              ? `0${Number(timeString.substring(3, timeString.length)) + 1}`
              : Number(timeString.substring(3, timeString.length)) + 1;
        } else {
          miumin = Number(time) + 1 == 24 ? "59" : "00";
          time =
            time[0] == 0 && time[1] != 9
              ? `0${Number(time) + 1}`
              : Number(time) + 1 == 24
                ? "23"
                : Number(time) + 1;
        }
        return [`${time}:${miumin}:59 - 23:59:59`];
      })()
    };
    if (this.form.trainNum) {
      this.getStationNumber({ type: 2, code: this.form.trainNum });
    }
    if (this.form.trainTime) {
      this.form.trainTime = this.$moment(this.form.trainTime).format("YYYY-MM-DD HH:mm:ss")
    }
    if (this.form.flyTime) {
      this.form.flyTime = this.$moment(this.form.flyTime).format("YYYY-MM-DD HH:mm:ss")
    }
  },
  methods: {
    handleInput () {
      this.destinationList.forEach((item, index) => {
        if (item.stationName === this.form?.trainTo) {
          this.toIndex = index;
          let arr = this.form.currentAddress;
          arr[1] = item;
          this.form.currentAddress = [...arr];
          return this.form.currentAddress;
        }
      });
      this.form.secondDeviceCode = this.form.trainNum;
      this.refreshPaterForm();
    },
    handleDeparture () {
      this.departureList.forEach((item, index) => {
        if (item.stationName === this.form.trainForm) {
          this.formIndex = index;
          let arr = this.form.currentAddress;
          arr[0] = item;
          this.form.currentAddress = [...arr];
          return this.form.currentAddress;
        }
      });
      this.form.secondDeviceCode = this.form.trainNum;
      this.refreshPaterForm();
    },
    handleElectronic (params, flag) {
      if (flag) {
        this.form.secondDeviceCode = params;
      } else {
        let address = [];
        address[0] = { stationName: params.city };
        this.form.currentAddress = [...address];
      }
    },
    handleSelect () {
      this.$emit("select", true);
    },
    // 火车车站获取，以及校验
    async getStation (type) {
      if (!this.form.flyNo && !this.form.trainNum) {
        this.departureList = [];
        this.destinationList = [];
        this.formIndex = null;
        this.toIndex = null;
        return false;
      }

      if (type === 1 && (!this.form.flyNo || !this.form.flyTime)) {
        // return this.$message.warning("请输入航班号和航班日期查询")
        return false;
      }
      if (type === 2) {
        this.form.trainForm = "";
        this.form.trainTo = "";
        if (this.form.currentAddress.length > 0) {
          this.form.currentAddress = [];
          this.form.secondDeviceCode = this.form.trainNum;
        }
      }

      let { code, data, message } = await ere.getThirdTrack({
        type,
        code: type === 1 ? this.form.flyNo : this.form.trainNum,
        date: type === 1 ? this.form.flyTime : this.form.trainTime
      });
      if (code !== 0) {
        this.form.flyNo = null;
        this.form.trainNum = null;
        return this.$message.error(message);
      }
      this.departureList = this.destinationList = data.stationList;
      if (this.form.checkValue === 1 && data.fromStation) {
        this.form.secondDeviceCode = data.code;
        this.form.currentAddress = [{ stationName: data.fromStation }, { stationName: data.toStation }];
      }
      this.refreshPaterForm();
    },
    // 获取车次站次
    async getStationNumber (params) {
      let { code, data, message } = await ere.getThirdTrack(params);
      if (code !== 0) {
        return this.$message.error(message);
      }
      data.stationList.some(
        (o, index) =>
        (this.formIndex =
          o.stationName === this.form.trainForm ? index : null)
      );
      data.stationList.some(
        (o, index) =>
          (this.toIndex = o.stationName === this.form.trainTo ? index : null)
      );
      this.departureList = this.destinationList = data.stationList;
    },
    // 航班日期早于发货时间处理
    handleFlyDate (value) {
      let valueFormat = this.$moment(value).format("YYYY-MM-DD HH:mm:ss");
      let fromTimeFormat = this.$moment(this.form.fromTime).format("YYYY-MM-DD HH:mm:ss");

      let toflag = returnCompareTime(new Date(valueFormat), new Date(fromTimeFormat));
      let a = valueFormat != fromTimeFormat;

      if (!toflag && value != "" && a) {
        return (this.form.flyTime = "");
      }
      if (this.form.flyNo) {
        this.getStation(1)
      }
      this.refreshPaterForm();
    },
    // 火车日期早于发货时间处理
    handleTrainDate (value) {
      let valueFormat = this.$moment(value).format("YYYY-MM-DD HH:mm:ss");
      let fromTimeFormat = this.$moment(this.form.fromTime).format("YYYY-MM-DD HH:mm:ss");

      let toflag = returnCompareTime(new Date(valueFormat), new Date(fromTimeFormat));
      let a = valueFormat != fromTimeFormat;

      if (!toflag && value != "" && a) {
        return (this.form.trainTime = "");
      }
      this.refreshPaterForm();
    },
    // 将form回传父组件
    refreshPaterForm () {
      this.$emit("refreshPaterForm");
    }
  }
};
</script>

<style lang="scss" scoped>
.supple-base-input {
  ::v-deep .el-form-item__label {
    width: 26% !important;
  }
  ::v-deep .el-form-item__content {
    display: flex;
  }
}
.btn {
  margin-bottom: 20px;
}
/deep/ .el-row {
  margin: 10px;
}
</style>
